using Microsoft.AspNetCore.Mvc;
using AdminSG3L.Applicaticn.Commands;
using Serilog;

namespace AdminSG3L.Api.Controllers;

/// <summary>
/// 健康检查控制器 - 提供系统状态监控
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class HealthController : ControllerBase
{
    /// <summary>
    /// 基础健康检查 - 不需要认证
    /// </summary>
    [HttpGet]
    public IActionResult Get()
    {
        try
        {
            var health = new
            {
                Status = "Healthy",
                Timestamp = DateTime.UtcNow,
                Version = "1.0.0",
                Environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development",
                Uptime = Environment.TickCount64 / 1000 // 秒
            };

            return Ok(ApiResponse<object>.Success(health, "系统运行正常"));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "HealthController.Get异常");
            return StatusCode(500, ApiResponse<object>.Fail("健康检查失败"));
        }
    }

    /// <summary>
    /// 详细健康检查 - 包含数据库和其他依赖项状态
    /// </summary>
    [HttpGet("detailed")]
    public IActionResult GetDetailed()
    {
        try
        {
            var health = new
            {
                Status = "Healthy",
                Timestamp = DateTime.UtcNow,
                Version = "1.0.0",
                Environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development",
                Uptime = Environment.TickCount64 / 1000,
                Dependencies = new
                {
                    Database = new { Status = "Connected", ResponseTime = "< 50ms" },
                    Cache = new { Status = "Available", ResponseTime = "< 10ms" },
                    ExternalServices = new { Status = "All Available" }
                },
                System = new
                {
                    Memory = new
                    {
                        Total = GC.GetTotalMemory(false),
                        Working = Environment.WorkingSet
                    },
                    Threads = System.Threading.ThreadPool.ThreadCount,
                    Processors = Environment.ProcessorCount
                }
            };

            return Ok(ApiResponse<object>.Success(health, "详细健康检查完成"));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "HealthController.GetDetailed异常");
            return StatusCode(500, ApiResponse<object>.Fail("详细健康检查失败"));
        }
    }

    /// <summary>
    /// 就绪检查 - Kubernetes 就绪探针使用
    /// </summary>
    [HttpGet("ready")]
    public IActionResult Ready()
    {
        // 这里可以添加更复杂的就绪检查逻辑
        // 例如检查数据库连接、缓存可用性等
        return Ok(new { status = "ready" });
    }

    /// <summary>
    /// 存活检查 - Kubernetes 存活探针使用
    /// </summary>
    [HttpGet("live")]
    public IActionResult Live()
    {
        return Ok(new { status = "alive" });
    }
}
